import React, { useState } from "react";
import Button from "@mui/material/Button";
import { TextField } from "@mui/material";
import "./login.less";
import logo from "@/assets/images/logo.png";
import { LoginApi } from "@/api";
import { useNavigate } from "react-router-dom";
import useToast, { useToastError } from "@/hooks/useToast";
// import Loading from "@/components/Loading";
// import { useDispatch } from "react-redux";
// import { Dispatch } from "redux";
export default function Login() {
  // 使用一个状态表示，当前是注册还登录
  const [isRegister, setIsRegister] = useState(false);
  const [username, setUsername] = useState("12345678901");
  const [password, setPassword] = useState("wolfcode123");
  const toast = useToast();
  const error = useToastError();

  const navigate = useNavigate();
  // useDispatch 是可以让我们决定传递什么样的action进去的
  // const dispatch = useDispatch<Dispatch<IToastAction>>();
  const register = () => {};
  const login = () => {
    LoginApi({
      username,
      password,
    })
      .then((res) => {
        if (res.errCode === 0) {
          // 提示用户
          toast("success", "登录成功");
          // 记录token
          localStorage.setItem("token", res.data);
          // 跳转到首页
          navigate("/home");
        }
      })
      .catch((err: any) => {
        error("登录失败");
      });
  };

  const btnClick = () => {
    // 在点击事件里面也要做防抖
    // 获取到输入框的内容，并且做一些数据校验
    isRegister ? register() : login();
  };
  return (
    <div className="login">
      <div className="logo">
        <img src={logo} alt="" />
      </div>
      <div className="row">
        <TextField
          fullWidth
          size="small"
          placeholder="请输入手机号"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
        />
      </div>
      <div className="row">
        <TextField
          fullWidth
          type="password"
          size="small"
          placeholder="请输入密码"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
      </div>
      <div className="row">
        <Button variant="contained" fullWidth onClick={btnClick}>
          {isRegister ? "注册" : "登录"}
        </Button>
      </div>
      <div className="row">
        <Button variant="text" onClick={() => setIsRegister(!isRegister)}>
          去{!isRegister ? "注册" : "登录"}
        </Button>
      </div>
      {/* <Loading /> */}
    </div>
  );
}
